package ltd.bugs.cute.channel.selector;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import ltd.bugs.cute.cache.CacheClient;
import ltd.bugs.cute.cache.callback.GetCallback;
import ltd.bugs.cute.channel.model.Channel;
import ltd.bugs.cute.channel.model.ClientChannelConfig;
import ltd.bugs.cute.channel.service.ChannelService;
import ltd.bugs.cute.channel.service.ClientChannelConfigService;
import ltd.bugs.cute.common.spring.ApplicationContextHolder;

/**
 * 通道选择器，根据
 * 
 * @author zhengzhq
 *
 */
public class ChannelSelector {

  private static ClientChannelConfigService clientChannelConfigService =
      ApplicationContextHolder.getBean(ClientChannelConfigService.class);
  private static ChannelService channelService =
      ApplicationContextHolder.getBean(ChannelService.class);

  /**
   * 获取最适合的通道，比如权重最高、价格最优
   * 
   * @param clientId 接入方标识
   * @param bizType 业务类型
   * @param excludeChannelIds 需要排除的通道id
   * @param selector 选择器
   * @return
   */
  public static Channel getExecuteChannel(long clientId, int bizType, List<Long> excludeChannelIds,
      Selector selector) {
    // 获取客户配置的所有启用通道
    List<Channel> availableChannels = getAvailableChannels(clientId, bizType);

    // 移除需要过滤的通道
    if (!CollectionUtils.isEmpty(excludeChannelIds)) {
      Iterator<Channel> it = availableChannels.iterator();
      while (it.hasNext()) {
        Channel channel = it.next();
        if (excludeChannelIds.contains(channel.getId())) {
          it.remove();
        }
      }
    }

    if (CollectionUtils.isEmpty(availableChannels)) {
      return null;
    }

    return selector.select(availableChannels);
  }

  /**
   * 根据客户id和业务类型获取可用（非停用）的通道列表
   * 
   * @param clientId
   * @param bizType
   * @return
   */
  private static List<Channel> getAvailableChannels(long clientId, int bizType) {
    return CacheClient.get(
        ClientChannelConfigService.keyUtil
            .getRecKey(".clientId." + clientId + ".type." + bizType + ".channels"),
        new GetCallback<List<Channel>>() {

          @Override
          public String getCacheGroup() {
            // 挂在所有通道的组下，任何一个通道有更新，数据重新获取
            return ChannelService.allChannelGroupKey;
          }

          @Override
          public List<Channel> getObject() {
            List<ClientChannelConfig> channelConfigs =
                clientChannelConfigService.get(clientId, bizType);
            if (CollectionUtils.isEmpty(channelConfigs)) {
              return Collections.emptyList();
            }

            // 过滤状态为启用的通道返回
            List<Channel> channels = new ArrayList<Channel>();
            for (ClientChannelConfig channelConfig : channelConfigs) {
              Channel channel = channelService.get(channelConfig.getChannelId());

              if (channel.getStatus() == Channel.STATUS_ENABLE) {
                // 拷贝创建新对象，避免ehcache直接修改引发内存数据的变更
                Channel newChannel = new Channel();
                BeanUtils.copyProperties(channel, newChannel);
                newChannel.setWeight(channelConfig.getWeight());
                channels.add(newChannel);
              }
            }

            return channels;
          }
        });
  }
}
